package com.example.partyplaner;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class TasksActivity extends ListActivity implements AsyncResponse{

	List<EventTask> tasksToDo;
	ArrayList<TaskList> tasksListToPass;
	ArrayList<Integer> organizerTask;
	ArrayAdapter<EventTask> adapter;
	static String value;
	private String responseMsg;
	private int responseCode;
	String taskListID;
	DatabaseConnection db;
	int getTasks;
	int logout=0;
	String filename="Tasks";
	FileOutputStream outputStream;
	FileInputStream inputStream;
	int start=0;
	int tasklists=0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tasks);
		tasksListToPass=new ArrayList<TaskList>();
		organizerTask=new ArrayList<Integer>();
		tasksToDo=new ArrayList<EventTask>();
		taskListID=null;
		getTasks=0;
		Bundle extras = getIntent().getExtras();
		if (extras != null) {

		    value = extras.getString("EVENT_ID");
		    db = new DatabaseConnection(TasksActivity.this);
			db.delegate = TasksActivity.this;
			
			db.execute("http://partyplanner.mais2014.cloudbees.net/rest/WebService/ListMyEvents", "GET" , MainActivity.token);
			start=0;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.tasks, menu);
		return true;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent intent = new Intent(getApplicationContext(),SingleTaskActivity.class);
		EventTask taskToPass=(EventTask) this.getListAdapter().getItem(position);
		intent.putExtra("TASK_ID", taskToPass);
		startActivity(intent);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.logout) {
			this.db = new DatabaseConnection(TasksActivity.this);
			this.db.delegate = TasksActivity.this;
			db.execute("http://partyplanner.mais2014.cloudbees.net/rest/WebService/Logout", "GET", MainActivity.token);
			logout=1;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void processFinish(WebserviceResponse output) {
		if(output!=null){
			responseMsg=output.getResponseMsg();
			responseCode=output.getResponseCode();
			Log.i("PartyPlanner", "process Finish");
			if (responseCode==200){
				if (logout!=1)
				{
					if (start==0)
					{
						try {
							start=1;
							JSONArray jArray = new JSONArray(responseMsg);
							for (int it = 0; it<jArray.length(); it++) {
								Log.i("PartyPlanner", "no of organizer task: "+jArray.getInt(it));
								organizerTask.add(jArray.getInt(it));
								Log.i("PartyPlanner","idies in array"+jArray.getInt(it));
								Log.i("PartyPlanner", "value"+value);
								int go=0;
								
								if(organizerTask.contains(Integer.parseInt(value))){
									tasklists=1;
									Log.i("PartyPlanner", "contains");
									db = new DatabaseConnection(TasksActivity.this);
									db.delegate = TasksActivity.this;
									db.execute("http://partyplanner.mais2014.cloudbees.net/rest/WebService/ShowTaskLists/"+MainActivity.token, "GET", value);		
								}
								else{
									Log.i("PartyPlanner", "NOT contains");
									tasklists=0;
									db = new DatabaseConnection(TasksActivity.this);
									db.delegate = TasksActivity.this;
									db.execute("http://partyplanner.mais2014.cloudbees.net/rest/WebService/ShowUsersTasks/"+MainActivity.token, "GET", value);		
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					else{
						if (tasklists==0){
							try {					
								JSONArray jArray = new JSONArray(responseMsg);
								if (!jArray.isNull(0)){
									for (int it = 0; it<jArray.length(); it++) {
										Log.i("PartyPlanner", "Array not null");
										JSONObject jObject= jArray.getJSONObject(it);
										Log.i("PartyPlanner",jObject.getString("title"));
										Log.i("PartyPlanner",jObject.getString("description"));
										EventTask task=new EventTask(jObject.getInt("ID"),jObject.getString("title"),"sad" ,jObject.getString("description") , jObject.getInt("realized"));
										tasksToDo.add(task);
									}
									try {
										outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
										ObjectOutputStream os;
										os = new ObjectOutputStream(outputStream);
										os.writeObject(jArray);
									} catch (IOException e) {
										e.printStackTrace();
									}
								}
								else{
									Log.i("PartyPlanner", "else");
									EventTask task1=new EventTask(0,"No tasks available", "","", 0);
									tasksToDo.add(task1);
								}
								
							} catch (JSONException e) {
								e.printStackTrace();
							}
							adapter = new ArrayAdapter<EventTask>(this,android.R.layout.simple_list_item_1, tasksToDo);
							setListAdapter(adapter);
						}
						else{
							try {					
								JSONArray jArray = new JSONArray(responseMsg);
								if (!jArray.isNull(0)){
									for (int it = 0; it<jArray.length(); it++) {
										Log.i("PartyPlanner", "task list gathering info");
										JSONObject jObject= jArray.getJSONObject(it);
										TaskList taskList=new TaskList(jObject.getInt("ID"),jObject.getInt("eventID"), jObject.getString("title"));
										tasksListToPass.add(taskList);
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
							Intent intent = new Intent(getApplicationContext(),TaskListActivity.class);
							intent.putExtra("TASK_LIST", tasksListToPass);
							startActivity(intent);
						}
					}
				}
				else{
					Intent intent = new Intent(getApplicationContext(),MainActivity.class);
					startActivity(intent);
				}
			}
			else{
				Log.i("PartyPlanner", "Fail");
			}	
		}
		else{
			Log.i("PartyPlanner", "NULL");
		}
	}
	
	public Dialog onCreateDialog(int dialogId) {
		switch (dialogId) {
			case MainActivity.PLEASE_WAIT_DIALOG:
				ProgressDialog dialog = new ProgressDialog(TasksActivity.this);
				dialog.setTitle("Connecting");
				dialog.setMessage("Please wait....");
				dialog.setCancelable(true);
				return dialog;
			default:
				break;
		}
		return null;
	}
}
